import { defineStore } from 'pinia';

export const useBoardStore = defineStore('app', {
  state: () => {
    return {
      pageIndex: 0, 
      pages: [], 
      undos: [], 
      redos: [], 
      cachePage: null, 
    }
  },
  actions: {
    
    setPage(index, page) {
      if(index >= this.pages.length) {
        this.pages.push(page);
      } else {
        this.pages[index] = page;
      }
      this.pageIndex = index;
    },
    
    addElement(ele) {
      if(this.undos.length >= 10) {
        this.undos.shift();
      } 
      this.undos.push(this.pages[this.pageIndex].ele);
      this.pages[this.pageIndex].ele = ele;

      this.redos = [];
    },

    lastPage(func) {
      const cache = { index: this.pageIndex, undos: this.undos, redos: this.redos };
      if(this.pageIndex > 0) {
        this.pageIndex -= 1;
      }
      if(func) func(this.pages[this.pageIndex].ele);
      if(this.cachePage && this.pageIndex === this.cachePage.index) { 
        this.undos = this.cachePage.undos;
        this.redos = this.cachePage.redos;
      } else {
        this.undos = [];
        this.redos = [];
      }
      this.cachePage = cache;
    },
    
    nextPage(func, emptyPage) { 
      const cache = { index: this.pageIndex, undos: this.undos, redos: this.redos };
      if(this.pageIndex < this.pages.length-1) {
        this.pageIndex += 1;
      } else {
        this.setPage(this.pageIndex+1, emptyPage);
      }
      if(func) func(this.pages[this.pageIndex].ele)
      if(this.cachePage && this.pageIndex === this.cachePage.index) { 
        this.undos = this.cachePage.undos;
        this.redos = this.cachePage.redos;
      } else {
        this.undos = [];
        this.redos = [];
      }
      this.cachePage = cache;
    },

    undo(func) {
      if(this.undos.length === 0) return;
      const ele = this.undos.pop(); 
      this.redos.push(this.pages[this.pageIndex].ele);
      this.pages[this.pageIndex].ele = ele;

      if(func) func(ele);
    },
    
    redo(func) {
      if(this.redos.length === 0) return;
      const ele = this.redos.pop(); 
      this.undos.push(this.pages[this.pageIndex].ele);
      this.pages[this.pageIndex].ele = ele;
      if(func) func(ele);
    },
    
    clear() {
      this.addElement('');
    }

  }
});